package com.bio.jsf;

import com.bio.jpa.entities.UserGroup;
import com.bio.jsf.util.JsfUtil;
import com.bio.jpa.session.UserGroupFacade;

import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import com.bio.jpa.entities.User;
import com.bio.jpa.entities.UserHasGroup;

@ManagedBean(name = "userGroupController")
@SessionScoped
public class UserGroupController implements Serializable {

    private UserGroup current = null;
    private List<UserGroup> usersGroups;
    private List<User> candidateUserList;
    private List<User> myUserList;
    private User currentUser;
    private UserHasGroup map;

    public User getCurrentUser() {
        return currentUser;
    }

    public void setCurrentUser(User selectedUser) {
        this.currentUser = selectedUser;
    }

    public List<User> getCandidateUserList() {
        candidateUserList = getFacade().findUsersInotIn(current.getGrId());
        return candidateUserList;
    }

    public void setCandidateUserList(List<User> candidateUserList) {
        this.candidateUserList = candidateUserList;
    }

    public List<User> getMyUserList() {
        myUserList = getFacade().findMyUsers(current.getGrId());
        return myUserList;
    }

    public void setMyUserList(List<User> myUserList) {
        this.myUserList = myUserList;
    }
    @EJB
    private com.bio.jpa.session.UserGroupFacade ejbFacade;

    public UserGroupController() {
    }

    public String remMeFromGroup(User u) {
        currentUser = u;
        map = new UserHasGroup(currentUser.getUserId(), current.getGrId());
        map.setUser(currentUser);
        map.setUserGroup(current);
        UserHasGroupController controller = (UserHasGroupController) FacesContext.getCurrentInstance().getApplication().getELResolver().
                getValue(FacesContext.getCurrentInstance().getELContext(), null, "userHasGroupController");
        if (controller.getUserItems().contains(map)) {
            controller.setCurrent(map);
            controller.getUserItems().remove(map);
            controller.destroy();
            System.out.println("trying to remove " + map);
        }
        return "View";
    }

    public String addMeToGroup() {
        map = new UserHasGroup(currentUser.getUserId(), current.getGrId());
        map.setUser(currentUser);
        map.setUserGroup(current);
        UserHasGroupController controller = (UserHasGroupController) FacesContext.getCurrentInstance().getApplication().getELResolver().
                getValue(FacesContext.getCurrentInstance().getELContext(), null, "userHasGroupController");
        if (!controller.getUserItems().contains(map)) {
            controller.setCurrent(map);
            controller.getUserItems().add(map);
            controller.create();
            System.out.println("trying to create " + map);
        } else {
            JsfUtil.addErrorMessage("User is already on this group");
        }
        return "View";
    }

    public void resetLists() {
        usersGroups = null;
        currentUser = null;
        currentUser = null;
        map = null;
    }

    public List<UserGroup> getUsersGroups() {
        if (usersGroups == null) {
            usersGroups = getFacade().findAll();
            usersGroups.remove(0);
        }
        return usersGroups;
    }

    public void setUsersGroups(List<UserGroup> usersGroups) {
        this.usersGroups = usersGroups;
    }

    public void setCurrent(UserGroup selected) {
        this.current = selected;
    }

    public UserGroup getCurrent() {
        if (current == null) {
            current = new UserGroup();
        }
        return current;
    }

    private UserGroupFacade getFacade() {
        return ejbFacade;
    }

    public String prepareList() {
        current = null;
        return "List";
    }

    public String prepareView() {
        return "View";
    }

    public String prepareCreate() {
        current = new UserGroup();
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            current = new UserGroup();
            resetLists();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UserGroupCreated"));
            return "List";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UserGroupUpdated"));
            return "List";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        performDestroy();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        return "List";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            current = null;
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UserGroupDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    @FacesConverter(forClass = UserGroup.class)
    public static class UserGroupControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            UserGroupController controller = (UserGroupController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "userGroupController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof UserGroup) {
                UserGroup o = (UserGroup) object;
                return getStringKey(o.getGrId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + UserGroupController.class.getName());
            }
        }
    }
}
